<template>
  <div class="box bg-gradient-to-r from-sky-500 to-indigo-500">
    <div class="login-box">
      <el-form ref="loginFormRef" size="large" :model="loginForm" :rules="rules" class="login-form">
        <h3 class="title">Trove Box</h3>
        <el-form-item label="用户名" label-width="75" prop="username">
          <el-input v-model="loginForm.username" :prefix-icon="User" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" label-width="75" prop="password">
          <el-input v-model="loginForm.password" :prefix-icon="Lock" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item class="control-btns">
          <el-button style="width: 100%" type="primary" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'

import { useUserStore } from '@/store/modules/user'

const loginFormRef = ref<FormInstance>()
const loginForm = ref({
  username: '',
  password: ''
})

const router = useRouter()
const userStore = useUserStore()
/**
 * 登录
 * @description 登录
 */
const handleLogin = () => {
  if (loginFormRef.value) {
    // 表单校验
    loginFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        // 登录
        const { username, password } = loginForm.value
        try {
          const loginRes = await userStore.login({ username, password })
          ElMessage.success(loginRes)
          router.push('/dashboard')
        } catch (error: any) {
          ElMessage.error(error)
        }
      }
    })
  }
}

/**
 * 登录表单校验规则
 * @description 登录表单校验规则
 */
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}
</script>

<style scoped lang="scss">
.box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;

  .login-box {
    width: 550px;
    height: 450px;
    padding: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #fff;
    border-radius: 5px;
    box-sizing: border-box;

    .login-form {
      width: 100%;

      .title {
        margin-bottom: 20px;
        font-size: 32px;
        font-weight: 800;
        text-align: center;
      }
    }
  }
}
</style>
